<template>
  <div>
    <div class="myRobot addKnowledgeBase">
      <robotNav></robotNav>
      <div class="myRobotRight">
        <div class="addKnowledgeBase_content">
          <div class="myRobotRight_title">
            <div class="myRobotRight_title_dd">添加知识库</div>
            <a href="#/alRobot/myRobotUserKnowledge/myRobotUserKnowledge" class="myRobotRight_title_btn notBlue">返回知识库</a>
          </div>
          <div class="addKnowledgeBase_content_nav">
            <div class="content_nav_list notBlue" @click="changeTab(1)" :class="{ active: activeTab === 1 }">
              <span><img src="@a/img/sv83on.svg"/><img src="@a/img/sv83.svg"/></span>网页
            </div>
            <div class="content_nav_list notBlue" @click="changeTab(2)" :class="{ active: activeTab === 2 }">
              <span><img src="@a/img/sv83on.svg"/><img src="@a/img/sv83.svg"/></span>指定网页
            </div>
            <div class="content_nav_list notBlue" @click="changeTab(3)" :class="{ active: activeTab === 3 }">
              <span><img src="@a/img/sv84on.svg"/><img src="@a/img/sv84.svg"/></span>站点地图
            </div>
            <div class="content_nav_list notBlue" @click="changeTab(4)" :class="{ active: activeTab === 4 }">
              <span><img src="@a/img/sv85on.svg"/><img src="@a/img/sv85.svg"/></span>文件
            </div>
          </div>
          <div class="addKnowledgeBase_content_con">
            <div v-if="activeTab == 1">
              <div class="content_con_link">
                <div class="con_link_title">网页网址</div>
                <div class="con_link_txt">
                  <div class="link_txt_left"><el-input v-model="url" placeholder="请输入内容"></el-input></div>
                  <div class="link_txt_right notBlue" :class="{ 'active': lodingShow }" @click="parseUrl">
                    <img v-show="!lodingShow" src="@a/img/sv111.svg"/>
                    <img v-show="lodingShow" src="@a/img/sv88.svg"/>
                    获取链接
                  </div>
                </div>
              </div>
              <div class="content_con_loding" v-show="lodingShow"><img src="@a/img/sv88.svg"/>正在获取链接...</div>
              <div class="content_con_href" v-show="hrefShow">
                <div class="con_href_title">找到{{ getCount() }}条链接</div>
                <div class="con_href_tab">
                  <div class="href_tab_title">
                    <div class="tab_title_li">
                      <input type="checkbox" class="notBlue" v-model="selectAllChecked" @change="toggleSelectAll">URL
                    </div>
                    <div class="tab_title_li">操作</div>
                  </div>
                  <div class="href_tab_txt">
                    <div class="tab_txt_list" v-for="(link, index) in links" :key="index">
                      <div class="txt_list_li">
                        <input type="checkbox" class="notBlue" v-model="link.checked" @change="updateSelectAll">
                        {{ link.url }}
                      </div>
                      <div class="txt_list_li">
                        <img src="@a/img/sv87.svg" class="delete notBlue" @click="deleteLink(index)">
                      </div>
                    </div>
                  </div>
                  <div class="href_tab_bottom">
                    <div class="tab_bottom_left"><img src="@a/img/sv89.svg"/>已选中{{ selectedCount }}个网址</div>
                    <div class="tab_bottom_right notBlue" @click="submitForm">开始训练</div>
                  </div>
                </div>
              </div>
            </div>
            <div v-if="activeTab == 2">
              <div class="content_con_link">
                <div class="con_link_title">指定网页网址</div>
                <div class="con_link_txt">
                  <div class="link_txt_left">
                    <el-input
                      type="textarea"
                      :rows="9"
                      placeholder="请输入内容"
                      v-model="urls">
                    </el-input>
                  </div>
                  <div class="link_txt_right notBlue" :class="{ 'active': lodingShow }" @click="addUrl">
                    <img v-show="!lodingShow" src="@a/img/sv111.svg"/>
                    <img v-show="lodingShow" src="@a/img/sv88.svg"/>
                    获取链接
                  </div>
                </div>
              </div>
              <div class="content_con_loding" v-show="lodingShow"><img src="@a/img/sv88.svg"/>正在获取链接...</div>
              <div class="content_con_href" v-show="hrefShow">
                <div class="con_href_title">找到{{ getCount() }}条链接</div>
                <div class="con_href_tab">
                  <div class="href_tab_title">
                    <div class="tab_title_li">
                      <input type="checkbox" class="notBlue" v-model="selectAllChecked" @change="toggleSelectAll">URL
                    </div>
                    <div class="tab_title_li">操作</div>
                  </div>
                  <div class="href_tab_txt">
                    <div class="tab_txt_list" v-for="(link, index) in links" :key="index">
                      <div class="txt_list_li">
                        <input type="checkbox" class="notBlue" v-model="link.checked" @change="updateSelectAll">
                        {{ link.url }}
                      </div>
                      <div class="txt_list_li">
                        <img src="@a/img/sv87.svg" class="delete notBlue" @click="deleteLink(index)">
                      </div>
                    </div>
                  </div>
                  <div class="href_tab_bottom">
                    <div class="tab_bottom_left"><img src="@a/img/sv89.svg"/>已选中{{ selectedCount }}个网址</div>
                    <div class="tab_bottom_right notBlue" @click="submitForm">开始训练</div>
                  </div>
                </div>
              </div>
            </div>
            <div v-if="activeTab == 3">
              <div class="content_con_link">
                <div class="con_link_title">站点地图网址</div>
                <div class="con_link_txt">
                  <div class="link_txt_left"><el-input v-model="url" placeholder="请输入内容"></el-input></div>
                  <div class="link_txt_right notBlue" :class="{ 'active': lodingShow }" @click="parseSiteMap">
                    <img v-show="!lodingShow" src="@a/img/sv111.svg"/>
                    <img v-show="lodingShow" src="@a/img/sv88.svg"/>
                    获取链接
                  </div>
                </div>
              </div>
              <div class="content_con_loding" v-show="lodingShow"><img src="@a/img/sv88.svg"/>正在获取链接...</div>
              <div class="content_con_href" v-show="hrefShow">
                <div class="con_href_title">找到{{ getCount() }}条链接</div>
                <div class="con_href_tab">
                  <div class="href_tab_title">
                    <div class="tab_title_li">
                      <input type="checkbox" class="notBlue" v-model="selectAllChecked" @change="toggleSelectAll">URL
                    </div>
                    <div class="tab_title_li">操作</div>
                  </div>
                  <div class="href_tab_txt">
                    <div class="tab_txt_list" v-for="(link, index) in links" :key="index">
                      <div class="txt_list_li">
                        <input type="checkbox" class="notBlue" v-model="link.checked" @change="updateSelectAll">
                        {{ link.url }}
                      </div>
                      <div class="txt_list_li">
                        <img src="@a/img/sv87.svg" class="delete notBlue" @click="deleteLink(index)">
                      </div>
                    </div>
                  </div>
                  <div class="href_tab_bottom">
                    <div class="tab_bottom_left"><img src="@a/img/sv89.svg"/>已选中{{ selectedCount }}个网址</div>
                    <div class="tab_bottom_right notBlue" @click="submitForm">开始训练</div>
                  </div>
                </div>
              </div>
            </div>
            <div v-if="activeTab == 4">
              <div class="content_con_link content_con_document">
                <div class="con_link_title">上传文件</div>

                <el-upload
                    class="upload-demo"
                    :action="this.baseURL + '/api1/robotFiles/upload'"
                    :headers="{ 'Authorization' : token}"
                    :before-upload="beforeUpload"
                    :on-success="handleSuccess"
                    :on-error="handleError"
                    :show-file-list="false"
                    multiple
                    :data="{'robot_id': this.$store.getters.robotId}"
                    >

                    <div class="con_document_txt notBlue" >
                      <img src="@a/img/sv90.svg"/>上传（支持pdf，word，txt）
                    </div>

                </el-upload>
              </div>
              <div class="content_con_loding" v-show="lodingShow"><img src="@a/img/sv88.svg"/>正在上传文件中...</div>
              <div class="content_con_href" v-show="hrefShow">
                <div class="con_href_title">共{{ getCount() }}个文件</div>
                <div class="con_href_tab">
                  <div class="href_tab_title">
                    <div class="tab_title_li">
                      <input type="checkbox" class="notBlue" v-model="selectAllChecked" @change="toggleSelectAll2">文件名称
                    </div>
                    <div class="tab_title_li">操作</div>
                  </div>
                  <div class="href_tab_txt">
                    <div class="tab_txt_list" v-for="(link, index) in links" :key="index">
                      <div class="txt_list_li">
                        <input type="checkbox" class="notBlue" v-model="link.checked" @change="updateSelectAll">
                        {{ link.url }}
                      </div>
                      <div class="txt_list_li">
                        <img src="@a/img/sv87.svg" class="delete notBlue" @click="deleteLink(index)">
                      </div>
                    </div>
                  </div>
<!--                  <div class="href_tab_txt">-->
<!--                    <div class="tab_txt_list" v-for="(document, index) in documents" :key="index">-->
<!--                      <div class="txt_list_li">-->
<!--                        <input type="checkbox" class="notBlue" v-model="document.checked" @change="updateSelectAll2">-->
<!--                        {{ document.name }}-->
<!--                      </div>-->
<!--                      <div class="txt_list_li">-->
<!--                        <img src="@a/img/sv87.svg" class="delete notBlue" @click="deleteDocument(index)">-->
<!--                      </div>-->
<!--                    </div>-->
<!--                  </div>-->
                  <div class="href_tab_bottom">
                    <div class="tab_bottom_left"><img src="@a/img/sv85.svg"/>已选中{{ selectedCount2 }}个文件</div>
                    <div class="tab_bottom_right notBlue" @click="confirmFiles">开始训练</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import robotNav from "@c/common/robotNav/robotNav";
  import { MessageBox, Message } from 'element-ui';
  import {api} from "@/api-js";
  import config from "@/config";

  export default {
    data() {
      return {
        activeTab: 1,
        url: '',
        urls: '',
        links: [
        ],
        documents: [
          { name: '文件1.pdf', checked: false },
          { name: '文件2.docx', checked: false },
          { name: '文件3.txt', checked: false },
        ],
        selectAllChecked: false, // 全选复选框的状态
        hrefShow: false,
        lodingShow: false,
        baseURL: config.baseurl,
        token: localStorage.getItem('token'),
      };
    },
    components: {
      robotNav
    },
    computed: {
      selectedCount() {
        return this.links.filter(link => link.checked).length;
      },
      selectedCount2() {
        return this.documents.filter(document => document.checked).length;
      },
    },
    methods: {
      addUrl() {
        let url = this.urls;
        if (url) {
          this.lodingShow = true;
          let urls = url.split('\n');
          this.links = [];
          urls.forEach(item => {
            this.links.push({ url: item, checked: true });
          })
          this.lodingShow = false;
          this.hrefShow = true;
        }else{
          this.$message.error('请输入网址');
        }
      },
      async parseSiteMap() {
        let url = this.url;
        if (url) {
          this.lodingShow = true;
          const [e,r] = await api.robotFiles.parseSiteMap(url);
          this.lodingShow = false;
          if(!e && r){
            this.links = [];
            r.result.forEach(item => {
              this.links.push({ url: item, checked: true });
            })
            this.hrefShow = true;
          }
        }else{
          this.$message.error('请输入网址');
        }
      },
      async parseUrl() {
        let url = this.url;
        if (url) {
          this.lodingShow = true;
          const [e,r] = await api.robotFiles.parseUrl(url);
          this.lodingShow = false;
          if(!e && r){
            this.links = [];
            r.result.forEach(item => {
              this.links.push({ url: item, checked: true });
            })
            this.hrefShow = true;
          }
        }else{
          this.$message.error('请输入网址');
        }
      },
      async submitForm() {
        let add_urls = [];
        this.links.forEach(item => {
          if(item.checked){
            add_urls.push(item.url)
          }
        })
        if(add_urls.length === 0){
          this.$message.error('请选择网址');
        }else{
          let data = {
            urls: add_urls,
            robot_id: this.$store.getters.robotId
          }
          const [e,r] = await api.robotFiles.addUrls(data);
          if(!e && r){
            this.$message.success('添加成功');
            this.closeDialog();
          }
        }
      },
      async confirmFiles() {
        let ids = [];
        this.links.forEach(item => {
          if(item.checked){
            ids.push(item.id)
          }
        })
        if(ids.length === 0){
          this.$message.error('请选择文件');
        }else{
          let data = {
            ids: ids,
            robot_id: this.$store.getters.robotId
          }
          const [e,r] = await api.robotFiles.confirmFiles(data);
          if(!e && r){
            this.$message.success('添加成功');
            this.closeDialog();
          }
        }
      },
      closeDialog(){
        //跳转到myRobotUserKnowledge
        this.$router.push({
          path: '/alRobot/myRobotUserKnowledge/myRobotUserKnowledge'
        })
      },
      changeTab(index) {
        this.activeTab = index;
        this.links = [];
        this.hrefShow = false;
        this.url = '';
        this.urls = '';
        if(index == 4){
          this.hrefShow = true;
        }
      },
      //链接
      toggleSelectAll() {
        this.links.forEach(link => link.checked = this.selectAllChecked);
      },
      updateSelectAll() {
        this.selectAllChecked = this.links.every(link => link.checked);
      },
      getCount() {
        return this.links.length;
      },
      //链接删除
      deleteLink(index) {
        MessageBox.confirm('确定要删除这条链接吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          Message.success('删除成功!');
          this.links.splice(index, 1);
        })
        .catch(() => {
          Message.info('已取消删除');
        });
      },
      //文件
      toggleSelectAll2() {
        this.documents.forEach(document => document.checked = this.selectAllChecked2);
      },
      updateSelectAll2() {
        this.selectAllChecked2 = this.documents.every(document => document.checked);
      },
      getCount2() {
        return this.documents.length;
      },
      //文件删除
      deleteDocument(index) {
        MessageBox.confirm('确定要删除这个文件吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          Message.success('删除成功!');
          this.documents.splice(index, 1);
        })
        .catch(() => {
          Message.info('已取消删除');
        });
      },
      //上传文件
      uploadFiles() {
        const inputElement = document.createElement('input');
        inputElement.type = 'file';
        inputElement.accept = '.pdf, .docx, .txt, application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        inputElement.multiple = true; // Enable multiple file selection
        inputElement.onchange = (event) => {
          const files = event.target.files; // Access the selected files
          for (let i = 0; i < files.length; i++) {
            const file = files[i];
            if (file) {
              const fileType = file.type;
              const fileSize = file.size;
              const maxSize = 10 * 1024 * 1024; // 10MB

              if (
                (fileType === 'application/pdf' ||
                  fileType === 'application/msword' ||
                  fileType === 'text/plain' ||
                  fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') &&
                fileSize <= maxSize
              ) {
                this.uploadFile(file);
              } else {
                if (fileType !== 'application/pdf' && fileType !== 'application/msword' && fileType !== 'text/plain' && fileType !== 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
                  alert('文件类型不支持，请选择pdf、word或txt文件');
                } else {
                  alert('文件大小超过限制，请选择小于10MB的文件');
                }
              }
            }
          }
        };
        inputElement.click();
      },
      uploadFile(file) {
        console.log('开始上传文件:', file.name);
        this.lodingShow = true;
        this.documentShow = true;

        // 模拟文件上传过程，延时2秒
        setTimeout(() => {
          console.log('文件上传完成:', file.name);
          this.lodingShow = false;
          this.documents.push({ name: file.name, checked: false });
        }, 2000);
      },
      beforeUpload(){

      },
      handleSuccess(p1, p2){
        console.log(p1, p2)
        let url = p2.name;
        let id = p2.response.result.id
        this.links.push({ url: url, checked: true, id: id });
      },
      handleError(p1, p2){
        console.log(p1, p2)
      },
    },
  }
</script>



<style>
@import "addKnowledgeBase.css";
</style>
